<?

//Initiate Authenticate
SecurityRedirect ();

//initiate Vars 
define("PRIMARY_KEY","group_id");
$FileName       = "ais_tools_access.php";
$FileTemplate   = "ais_tools_access_form.html";
$SubHeaderTitle = "Access Modules Management";
$TableName			= "tblgroup";
$HTMLFormName   = "UserForm";
$HTMLGridList  	=  "ModuleAccessGrid";

$FormAction    = $FileName . "?" . AddParam(GetQueryString("QueryString", ""),"form","$HTMLFormName");
$FormEncType   = "application/x-www-form-urlencoded";
//$PMode       = "";

//Initiate Database Table For Insert & Update;
$FormFields    = array("group_id","group_code","group_name");
buildsqlfield ("$TableName", $FormFields);

//Leave Here Untouch
$FormCName     = BuildHTMLField($FormFields,"name");
$FormCValue    = BuildHTMLField($FormFields,"value");

//************ FORM ACTION **************
$GroupID       = GetParam("group_id","");
$RecCount = $DBConnection->dbc->get_var("SELECT COUNT(*) FROM tblmodules");
//print $RecCount;
if (GetParam("form","")==$HTMLFormName) {
	if (GetParam("Action","")=="Save") {
		FormSave();
	}
}

//Field Verification 
$Verification  = "Enable";
$SessionVar    = md5(microtime());
//$SessionVar  = "Stuck";
$VerifyFields  = array("group_code"=>"Group Code","group_name"=>"Group Name");
VerifyHTML ($HTMLFormName,$VerifyFields,$SessionVar);

//************ SET FORM MODE ***************

if (GetParam(PRIMARY_KEY,"")) $FormMode = "Edit";
else $FormMode = "Add";

//******* DATABASE FORM QUERY ***********
$SQL = "SELECT * FROM `$TableName`";
if (GetParam(PRIMARY_KEY,"") && $FormMode="Edit") {
    $SQLForm = $SQL."WHERE ".PRIMARY_KEY."='".GetParam(PRIMARY_KEY,"")."'";
}

//Query Module
$SQLMod = "SELECT * FROM tblmodules ORDER BY module_order";

//******* SHOW FORM CONTENT *********
$TBS = new clsTinyButStrong ;
$TBS->LoadTemplate($MOD_TEMPLATE_DIR."/".$FileTemplate);

//HTML Component Data

//HTML Value From Database
//print $SQLForm;
if (GetParam(PRIMARY_KEY,"")) $TBS->MergeBlock("blv","mysql",$SQLForm);
else $TBS->MergeBlock("blv",$FormCValue);
SelectModuleByGroup(GetParam("group_id",""));
$Result = ModulesList ("", "", 0, 0);
//HTML Component Name
$TBS->MergeBlock("blmod",$Result);
$TBS->MergeBlock("bln",$FormCName);
$TBS->Show();


//*************** ACTION FUNCTION *******************
function FormSave() {
	global $DBConnection,$FileName,$RecCount;
	$count = $DBConnection->dbc->get_var("SELECT COUNT(*) FROM tblaccess WHERE group_id=".GetParam("group_id",""));
	if (($count==0) || ($RecCount<>$count)) {
		$DBConnection->dbc->query("DELETE FROM tblaccess WHERE group_id=".GetParam("group_id",""));	
	}
	for ($x=1;$x<=$RecCount;$x++) {
		if (GetParam("mod_idx".$x,"")) {
			if (($count==0) || ($RecCount<>$count)) {
				$DBConnection->dbc->query("INSERT INTO tblaccess VALUES ('".GetParam("group_id","")."','".GetParam("mod_idx".$x,"")."','".GetParam("insertCheck".$x,"")."','".GetParam("updateCheck".$x,"")."','".GetParam("deleteCheck".$x,"")."','".GetParam("noaccessCheck".$x,"")."','".GetParam("appr1Check".$x,"")."','".GetParam("appr2Check".$x,"")."','".GetParam("appr3Check".$x,"")."')");
			} else {
				$DBConnection->dbc->query("UPDATE tblaccess SET `m_insert`='".GetParam("insertCheck".$x,"")."',`m_update`='".GetParam("updateCheck".$x,"")."',`m_delete`='".GetParam("deleteCheck".$x,"")."',`noaccess`='".GetParam("noaccessCheck".$x,"")."',`approval1`='".GetParam("appr1Check".$x,"")."',`approval2`='".GetParam("appr2Check".$x,"")."',`approval3`='".GetParam("appr3Check".$x,"")."' WHERE group_id='".GetParam("group_id","")."' AND module_id='".GetParam("mod_idx".$x,"")."'");
			}
			//$DBConnection->dbc->debug();
		}
	}

	Forward($FileName."?group_id=".GetParam("group_id","")."&PageMode=Form");
}

function FormInsert() {
	global $DBConnection,$FileName;
	$DBConnection->Insert();
	header("Location: $FileName?PageMode=Form");
	exit;
}

function FormUpdate() {
	global $DBConnection;
	$DBConnection->Update();
}

function FormDelete() {
	global $DBConnection,$FileName,$TableName;
	$DBConnection->Delete("$TableName",PRIMARY_KEY);
	header("Location: $FileName");
	exit;	
}

function FormSearch () {

}

function FormCancel () {
	global $FileName;
	header("Location: ".$FileName);
	exit;
}

//*************** USER FUNCTION *******************
function buildsqlfield ($table, $arrayfield, $ExcludeField="") {
		global $DBConnection;
		$x_field = explode(";",$ExcludeField);
		
		for ($x=0;$x<count($arrayfield);$x++) {
			if (!in_array($arrayfield[$x],$x_field)) 
			   $DBConnection->add_htmlfield($table,$arrayfield[$x],GetParam($arrayfield[$x],""));
		}
}

function SelectModuleByGroup($GroupID) {
	global $DBConnection;
	$SQL = "DROP TABLE IF EXISTS `tblaccess_bygroup`;";
	$DBConnection->dbc->query($SQL);
	$SQL = "
	CREATE TEMPORARY TABLE `tblaccess_bygroup` (
	  `group_id` int(11) default NULL,
	  `module_id` int(11) default NULL,
	  `m_insert` tinyint(3) unsigned NOT NULL default '0',
	  `m_update` tinyint(3) unsigned NOT NULL default '0',
	  `m_delete` tinyint(3) unsigned NOT NULL default '0',
	  `noaccess` tinyint(3) unsigned NOT NULL default '0',
	  `approval1` tinyint(3) unsigned NOT NULL default '0',
      `approval2` tinyint(3) unsigned NOT NULL default '0',
      `approval3` tinyint(3) unsigned NOT NULL default '0'
	) TYPE=MyISAM;
	 ";
	$DBConnection->dbc->query($SQL);
	$SQL = "INSERT INTO tblaccess_bygroup SELECT * FROM tblaccess WHERE group_id=".$GroupID;
	$DBConnection->dbc->query($SQL);
}

function ModulesList ($Space, $Index, $ParentID) {
	    global $FileName,$TableName,$RS,$Index,$counter;
		if (!$Index) $Index = 0;
	    $DBConnection = new mydb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
	    if ($ParentID) $WHERE = "WHERE parent_module_id=$ParentID";
	    else $WHERE = "WHERE ifnull(parent_module_id,0) = 0 ";
		$SQL = "SELECT tblmodules.*,tblaccess_bygroup.m_insert,tblaccess_bygroup.m_update,tblaccess_bygroup.m_delete,tblaccess_bygroup.noaccess,tblaccess_bygroup.approval1,tblaccess_bygroup.approval2,tblaccess_bygroup.approval3 ".
		       "FROM tblmodules ".
		       "LEFT JOIN tblaccess_bygroup ON tblmodules.module_id=tblaccess_bygroup.module_id ".
		       $WHERE." ORDER BY module_order";

		//print $SQL."<br><br>\n\n\n\n";
		$MyResult = $DBConnection->dbc->get_results($SQL,ARRAY_A);
		if ($MyResult){
			foreach ($MyResult as $RowResult) {
				$counter++;

				if ($RowResult["parent_module_id"]=='') $RowResult["module_name"] = "<b>".$RowResult["module_name"]."</b>";
				if ($RowResult["m_insert"]=='1') $RowResult["ins_ck"] = "checked";
				else $RowResult["ins_ck"] = "";
				if ($RowResult["m_update"]=='1') $RowResult["upd_ck"] = "checked";
				else $RowResult["upd_ck"] = "";
				if ($RowResult["m_delete"]=='1') $RowResult["del_ck"] = "checked";
				else $RowResult["del_ck"] = "";
				if ($RowResult["noaccess"]=='1') $RowResult["no_ck"] = "checked";
				else $RowResult["no_ck"] = "";
				if ($RowResult["approval1"]=='1') $RowResult["apr1_ck"] = "checked";
				else $RowResult["apr1_ck"] = "";
				if ($RowResult["approval2"]=='1') $RowResult["apr2_ck"] = "checked";
				else $RowResult["apr2_ck"] = "";
				if ($RowResult["approval3"]=='1') $RowResult["apr3_ck"] = "checked";
				else $RowResult["apr3_ck"] = "";

				$RowResult["insFlag"]="";
				$RowResult["updFlag"]="";
				$RowResult["delFlag"]="";
				$RowResult["apr1Flag"]="";
                                $RowResult["apr2Flag"]="";
                                $RowResult["apr3Flag"]="";
				$RowResult["modFlag"]="";

				if (ereg("Insert",   $RowResult["module_access"]))
					$RowResult["insFlag"]="<input type=\"checkbox\" name=\"insertCheck$counter\" id=\"insertCheck$counter \"value=\"1\" ".$RowResult["ins_ck"]." class=\"inputRadio\">Insert";
				if (ereg("Update",   $RowResult["module_access"]))
					$RowResult["updFlag"]="<input type=\"checkbox\" name=\"updateCheck$counter\" id=\"updateCheck$counter \"value=\"1\" ".$RowResult["upd_ck"]." class=\"inputRadio\">Update";
				if (ereg("Delete",   $RowResult["module_access"]))
					$RowResult["delFlag"]="<input type=\"checkbox\" name=\"deleteCheck$counter\" id=\"deleteCheck$counter \"value=\"1\" ".$RowResult["del_ck"]." class=\"inputRadio\">Delete";
				if (ereg("Approval1", $RowResult["module_access"])) 
					$RowResult["apr1Flag"]="<input type=\"checkbox\" name=\"appr1Check$counter\" id=\"appr1Check$counter \"value=\"1\" ".$RowResult["apr1_ck"]." class=\"inputRadio\" >Appr.1";
				if (ereg("Approval2", $RowResult["module_access"]))
					$RowResult["apr2Flag"]="<input type=\"checkbox\" name=\"appr2Check$counter\" id=\"appr2Check$counter \"value=\"1\" ".$RowResult["apr2_ck"]." class=\"inputRadio\" >Appr.2";
				if (ereg("Approval3", $RowResult["module_access"]))
					$RowResult["apr3Flag"]="<input type=\"checkbox\" name=\"appr3Check$counter\" id=\"appr3Check$counter \"value=\"1\" ".$RowResult["apr3_ck"]." class=\"inputRadio\" >Appr.3";
				if (strlen(trim($RowResult["module_access"])) || (ereg("View", $RowResult["module_access"])))
					$RowResult["modFlag"]="<input type=\"checkbox\" name=\"noaccessCheck$counter\" id=\"noaccessCheck$counter\" value=\"1\" ".$RowResult["no_ck"]." class=\"inputRadio\">Forbiden";

				
				$RowResult["module_name"] = $Space.$RowResult["module_name"];
				//print $RowResult["module_name"]."<br>\n\n";
				$RS[$Index] = $RowResult;
//				print $RS[$Index]["module_name"]."$Index<br>\n\n";
				$Index++;
				ModulesList ($Space."&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", $Index, $RowResult["module_id"]);
			}
		}
	return $RS;
} 

?>